package com.hjx.demo.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

/**
 * 响应结果
 *
 * @author zhaozheng
 */
public class DemoResponse {

    private OutputStream output;

    private DemoRequest request;

    private static final int BUFFER_SIZE = 1024;

    public DemoResponse(OutputStream output) {
        this.output = output;
    }

    public void setRequest(DemoRequest request) {
        this.request = request;
    }

    //发送一个静态资源给客户端，若本地服务器有对应的文件则返回，否则返回404页面
    public void sendStaticResource() {
        byte[] buffer = new byte[BUFFER_SIZE];
        int ch;
        FileInputStream fis = null;
        try {
            File file = new File(DemoHttpServer.WEB_ROOT, request.getUri());
            if (file.exists()) {
                output.write("HTTP/1.1 200 OK \r\n".getBytes());
                output.write("Server: myServer/1.0\r\n".getBytes());
                output.write(("Date: " + new Date().toString() + "\r\n").getBytes());
                output.write("Content-Type: text/html;charset=utf-8\r\n".getBytes());
                output.write("\r\n".getBytes());
                fis = new FileInputStream(file);
                ch = fis.read(buffer);
                while (ch != -1) {
                    output.write(buffer, 0, ch);
                    ch = fis.read(buffer, 0, BUFFER_SIZE);
                }
            } else {
                output.write("HTTP/1.1 404 File NOT Found\r\n".getBytes());
                output.write("Server: myServer/1.0\r\n".getBytes());
                output.write(("Date: " + new Date().toString() + "\r\n").getBytes());
                output.write("Content-Type: text/html;charset=utf-8\r\n".getBytes());

                String errorMessage = "HTTP/1.1 404 File Not Found \r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 24\r\n" +
                        "\r\n" +
                        "<h1>File Not Found!</h1>";
                output.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}